package md.NJavaBase;

import android.util.Log;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class MainLoop {
    //初始化
    public static void Go()
    {
        Timer timer = new Timer();// 实例化Timer类
        class  task extends TimerTask
        {
            public task(Timer timer )
            {
                m_timer = timer;
            }

            public void run() {
                class reloadRunnable implements Runnable
                {
                    @Override public void run() {
                        DoLoop();
                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  reloadRunnable( ));
            }

            Timer m_timer;
        }
        timer.schedule(new task( timer) , 1000,1000);// 毫秒
    }

    //启动一个循环
    public static void StartLoop(ILoop loop)
    {
        mList.add( loop );
    }

    //执行循环队列
    static void DoLoop()
    {
        ArrayList<ILoop> copyList = (ArrayList<ILoop>) mList.clone();
        mList.clear();

        int len = copyList.size();
        for(int i=0;i<len;i++)
        {
            ILoop curr = copyList.get(i);
            try {
                if (curr.Do()) mList.add(curr);
            }catch (Exception ex)
            {
                Log.e("MainLoop",ex.toString());
            }
        }
    }

    static ArrayList<ILoop> mList = new ArrayList<ILoop>();
}
